use Mojo::mysql;
use Mojo::JSON qw(decode_json encode_json);
use strict;

my $mysql = Mojo::mysql->strict_mode('mysql://dahama:xxxxxxxxxx@/vpninfo');

my $db = $mysql->db;

sub show_vpn_account {
    my $user = shift; #在Mojo中从session获取
    my $company_id = shift;
    my $user_info = $db->query('select sbu_id,userrole from admin_account where username=?',$user)->array;
    my $show_right = $db->query('select number from sbu_company_relation where sbu=?,role=?',$user_info->[0],$user_info->[1])->array;
    if ($show_right->[0]){
        my $hashes = $db->query('select username,description,tibaoren,chuli,guanliyuanshenhe,xitongchuli,chuliyijian from vpn_account where company_id=?',$company_id)->hashes;
        print $hashes->[0]->{username},"查询成功\n"; #在Mojo中向前端发送JSON数据渲染
    }else{
        print "错误，你所查找的公司信息在您的事业部不存在！\n"; #在Mojo中向前发送JSON数据渲染
    }
}

sub add_vpn_account {
    my $user = shift; #在Mojo中从session获取
    #my $json = shift; #前端获取JSON数据（包括公司ID、用户名、密码、公司全称）
    my $company_id = shift;
    my $username = shift;
    my $password = shift;
    my $description = shift;
    my $is_exist = $db->query('select company_id from vpn_account where username=?',$username)->array;
    if ($is_exist->[0]){
        my $existed_info = $db->query('select role,sbu from sbu_company_relation where company_id=?',$is_exist->[0])->array;
        print "该账户$username已由$existed_info->[1]的$existed_info->[0]注册\n"; #在Mojo中render渲染
    }else{
        $db->query('insert into vpn_account (username,company_id,password,shijian,tibaoren,chuli,guanliyuanshenhe,xitongchuli,description) values (?,?,?,time(),?,1,0,0,?)',$username,$company_id,$password,$user,$description);
        print "账户添加成功，等待管理员审核"; #Mojo渲染
    }
}

sub del_vpn_account {
    my $username = shift;
    my $is_exist = $db->query('select guanliyuanshenhe from vpn_account where username=?',$username)->array;
    if($is_exist->[0] != 1) {
        $db->query('update vpn_account set guanliyuanshenhe=1,xitongchuli=1,chuli=0 where username=?',$username);
    }else{
        $db->query('update vpn_account set guanliyuanshenhe=0,xitongchuli=0,chuli=0 where username=?',$username);
    }
    print "删除成功\n"; #Mojo Render
}